<template>
  <div class="ml-2 flex-1">
    <div>
      <a-card :bordered="false" style="height: 830px; width: 1380px">
        <a-segmented v-model:value="value" :options="data" />
        <template v-if="value === '收费导出'">
          <a-form layout="inline" :model="searchForm" class="mt-3">
            <a-form-item label="收费期">
              <a-date-picker v-model:value="searchForm.yearRange" format="YYYY" picker="year" />
            </a-form-item>
            <a-form-item>
              <a-button type="primary" :icon="h(SearchOutlined)" @click="onSearch(0)">生成按面积离线收费数据</a-button>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" :icon="h(SearchOutlined)" @click="onSearch(1)">生成按计量离线收费数据</a-button>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" :icon="h(HistoryOutlined)" @click="onHistory">导出历史</a-button>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" :icon="h(CloudDownloadOutlined)" @click="onList">导出收费信息</a-button>
            </a-form-item>
          </a-form>
          <a-table :columns="columns" :data-source="dataSource" :row-class-name="(_record: any, index: number) =>
            index % 2 === 1 ? 'table-striped' : null
            " :pagination="pagination" :scroll="{ x: 3000, y: 550 }" bordered class="mt-5"></a-table>
        </template>
        <template v-if="value === '收费导入'">
          <a-form layout="inline" :model="searchForm" class="mt-3">
            <a-form-item label="操作人" name="operator">
              <a-tree-select v-model:value="searchForm.operator" tree-data-simple-mode allow-clear style="width: 120px"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" :tree-data="selectList" placeholder="请选择操作人"
                :load-data="onLoadData" />
            </a-form-item>
            <a-form-item label="归属机构" name="comId">
              <a-tree-select v-model:value="searchForm.comId" tree-node-filter-prop="label" style="width: 120px"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" :tree-data="comanyList"
                placeholder="请选择归属机构" />
              <!-- <a-tree-select
                v-model:value="searchForm.comId"
                style="width: 320px"
                :tree-data="comanyList"
                allow-clear
                placeholder="请选择归属机构"
                tree-node-filter-prop="label"
                :load-data="onLoadDatas"
                tree-checkable
              /> -->
            </a-form-item>
            <a-form-item label="文件名" name="fileName">
              <a-input v-model:value="searchForm.fileName"></a-input>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" :icon="h(SearchOutlined)" @click="onFeeRecord">查询</a-button>
            </a-form-item>
            <a-form-item>
              <!-- <a-button
                type="primary"
                :icon="h(CloudUploadOutlined)"
                @click="onImport"
                >按计量导入收费数据</a-button
              > -->
              <a-upload v-model:file-list="fileList" name="file" action="/api/ChargeSystem/SFGL/saveMeterPayFeeData"
                :showUploadList="false">
                <a-button type="primary">
                  <CloudUploadOutlined></CloudUploadOutlined>
                  按计量导入收费数据
                </a-button>
              </a-upload>
            </a-form-item>
            <a-form-item>
              <!-- <a-button
                type="primary"
                :icon="h(CloudUploadOutlined)"
                @click="onImportArea"
                >按面积导入收费数据</a-button
              > -->
              <a-upload v-model:file-list="fileList" name="file" action="/api/ChargeSystem/SFGL/savePayFeeData"
                :showUploadList="false">
                <a-button type="primary">
                  <CloudUploadOutlined></CloudUploadOutlined>
                  按计量导入收费数据
                </a-button>
              </a-upload>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" :icon="h(CloudDownloadOutlined)" @click="onTemplate">导入模版</a-button>
            </a-form-item>
          </a-form>
          <a-table :columns="importColumns" :data-source="importDataSource" :row-class-name="(_record: any, index: number) =>
            index % 2 === 1 ? 'table-striped' : null
            " :pagination="importPagination" :scroll="{ x: 1700, y: 550 }" bordered class="mt-5">
            <template #bodyCell="{ column, record, text }">
              <template v-if="column.dataIndex === 'delStatus'">
                <a-tag :bordered="false" color="success" v-if="record.delStatus == 1">成功</a-tag>
                <a-tag :bordered="false" color="error" v-if="record.delStatus == 0">失败</a-tag>
              </template>
              <template v-if="column.dataIndex === 'active'">
                <a-button type="link" @click="onDown(record)">下载</a-button>
                <a-popconfirm title="确定要删除吗？" placement="bottom" ok-text="是" cancel-text="否" @confirm="onDel(record)">
                  <a-button type="link" danger>删除</a-button>
                </a-popconfirm>
              </template>
            </template>
          </a-table>
        </template>
      </a-card>
    </div>
    <a-modal v-model:open="isHistory" title="导出历史" :footer="null" width="1200px">
      <a-table :columns="historyColumns" :data-source="historyDataSource" bordered :pagination="historyPagination"
        class="mt-3" :row-class-name="(_record: any, index: number) =>
          index % 2 === 1 ? 'table-striped' : null
          ">
        <template #bodyCell="{ column, record, text }">
          <template v-if="column.dataIndex === 'states'">
            <a-tag :bordered="false" color="success" v-if="record.states == '0'">完成</a-tag>
            <a-tag :bordered="false" color="error" v-else>失败</a-tag>
          </template>
          <template v-if="column.dataIndex === 'active'">
            <a-button type="link" @click="onDown(record)">下载</a-button>
          </template>
        </template>
      </a-table>
    </a-modal>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, h } from "vue";
import {
  HistoryOutlined,
  SearchOutlined,
  CloudUploadOutlined,
  CloudDownloadOutlined,
} from "@ant-design/icons-vue";
import { getOperatorApi } from "#/api/core/statistical";
import { getCompanyTree } from "#/api/core/develop";
import {
  getOfflineHeatFeeApi,
  getOfflineHeatFeeListApi,
  getOfflineHeatFeeHistoryApi,
  importOfflineHeatFeeApi,
  importOfflineHeatFee2Api,
  getOfflineHeatFeeImportRecordApi,
  delOfflineHeatFeeImportRecordApi,
} from "#/api/core/charge";
import dayjs from "dayjs";
import { message } from "ant-design-vue";

const props = defineProps({
  selectedNodeId: {
    type: String,
    default: "",
  },
});
const areaType = ref();
const isHistory = ref(false);
const data = reactive(["收费导出", "收费导入"]);
const value = ref("收费导出");
const searchForm = reactive({
  yearRange: "",
  operator: "",
  comId: "",
});
const comanyList = ref([]);
const getTableData = () => {
  getCompanyTree().then((res: any) => {
    // console.log(res);
    // 递归处理树形数据，保持层级结构
    const processTreeData = (tree: any[]): any[] => {
      console.log(tree);
      return tree.map((item: any) => {
        const processedItem = {
          key: item.id,
          label: item.name,
          value: item.id,
          isLeaf: item.children && item.children.length > 0 ? false : true,
          children: [],
        };

        // 如果存在children，递归处理子节点
        if (item.children && item.children.length > 0) {
          processedItem.children = processTreeData(item.children);
        }

        return processedItem;
      });
    };

    const treeData = processTreeData([res.data]);
    comanyList.value = treeData;
    console.log(comanyList.value);
  });
};
const selectList = ref([]);
const getList = () => {
  getOperatorApi(null)
    .then((res: any) => {
      console.log(res);
      selectList.value = res.map((item: any) => {
        return {
          id: item.id,
          value: item.id,
          title: item.name,
          key: item.id,
          isLeaf: !!item.userId, // 如果有userId说明是叶子节点
        };
      });
    })
    .catch((error) => {
      console.error("获取操作人员列表失败:", error);
      message.error("获取操作人员列表失败");
    });
};
getList();
getTableData();
const onLoadData = (treeNode: any) => {
  return new Promise((resolve) => {
    console.log(treeNode);
    // 如果是叶子节点，直接返回
    if (treeNode.isLeaf) {
      resolve(undefined);
      return;
    }

    // 加载子节点数据
    getOperatorApi(treeNode.id)
      .then((res: any) => {
        const children = res.map((item: any) => {
          console.log(item);
          return {
            id: item.userId ? item.userId : item.id,
            value: item.name ? item.name : item.name,
            title: item.name,
            key: item.userId ? item.userId : item.id,
            isLeaf: !!item.userId, // 如果有userId说明是叶子节点
          };
        });

        // 找到对应的节点并更新其children
        const updateNode = (nodes: any[]) => {
          for (let node of nodes) {
            if (node.key === treeNode.id) {
              node.children = children;
              return true;
            }
            if (node.children && updateNode(node.children)) {
              return true;
            }
          }
          return false;
        };

        updateNode(selectList.value);
        selectList.value = [...selectList.value];
        console.log(selectList.value);
        resolve(undefined);
      })
      .catch((error) => {
        console.error("加载子节点失败:", error);
        message.error("加载子节点失败");
        resolve(undefined);
      });
  });
};
const dataSource = ref([]);
const columns = [
  {
    title: "小区名称",
    dataIndex: "village",
    key: "village",
    align: "center",
    width: 120,
  },
  {
    title: "小区地址",
    dataIndex: "houseAddress",
    key: "houseAddress",
    align: "center",
    width: 150,
  },
  {
    title: "用户姓名",
    dataIndex: "holder",
    key: "holder",
    align: "center",
    width: 100,
  },
  {
    title: "热力卡号",
    dataIndex: "alipayConsNo",
    key: "alipayConsNo",
    align: "center",
    width: 120,
  },
  {
    title: "收费期",
    dataIndex: "year",
    key: "year",
    align: "center",
    width: 100,
  },
  {
    title: "面积名称",
    dataIndex: "areaName",
    key: "areaName",
    align: "center",
    width: 100,
  },
  {
    title: "收费面积",
    dataIndex: "feeArea",
    key: "feeArea",
    align: "center",
    width: 100,
  },
  {
    title: "单价",
    dataIndex: "price",
    key: "price",
    align: "center",
    width: 100,
  },
  {
    title: "应收全费金额",
    dataIndex: "normalReceivable",
    key: "normalReceivable",
    align: "center",
    width: 120,
  },
  {
    title: "应收基本费金额",
    dataIndex: "heatWasteReceivable",
    key: "heatWasteReceivable",
    align: "center",
    width: 120,
  },
  {
    title: "应收减免金额",
    dataIndex: "receivableDerate",
    key: "receivableDerate",
    align: "center",
    width: 120,
  },
  {
    title: "已收金额",
    dataIndex: "yjTotal",
    key: "yjTotal",
    align: "center",
    width: 100,
  },
  {
    title: "实际已收",
    dataIndex: "realReceiveToal",
    key: "realReceiveToal",
    align: "center",
    width: 100,
  },

  {
    title: "折扣金额",
    dataIndex: "totalDiscountMoney",
    key: "totalDiscountMoney",
    align: "center",
    width: 100,
  },
  {
    title: "退款金额",
    dataIndex: "refundTotal",
    key: "refundTotal",
    align: "center",
    width: 100,
  },
  {
    title: "拖欠热费金额",
    dataIndex: "arrearage",
    key: "arrearage",
    align: "center",
    width: 100,
  },
  {
    title: "拖欠金额",
    dataIndex: "arrearageTotal",
    key: "arrearageTotal",
    align: "center",
    width: 100,
  },
  {
    title: "抹零金额",
    dataIndex: "zeroAmount",
    key: "zeroAmount",
    align: "center",
    width: 100,
  },
  {
    title: "已开发票金额",
    dataIndex: "",
    key: "",
    align: "center",
    width: 120,
  },
  {
    title: "已开收据金额",
    dataIndex: "",
    key: "",
    align: "center",
    width: 120,
  },
  {
    title: "应收违约金",
    dataIndex: "lateFeeRealReceive",
    key: "lateFeeRealReceive",
    align: "center",
    width: 120,
  },
  {
    title: "违约金减免金额",
    dataIndex: "lateFeeDerate",
    key: "lateFeeDerate",
    align: "center",
    width: 130,
  },
  {
    title: "违约金实收",
    dataIndex: "lateFeeRealReceive",
    key: "lateFeeRealReceive",
    align: "center",
    width: 120,
  },
  // {
  //   title: "操作",
  //   dataIndex: "action",
  //   key: "action",
  //   align: "center",
  //   fixed: "right",
  //   width: 200,
  // },
];
const historyColumns = [
  {
    title: "文件名",
    dataIndex: "fileName",
    key: "fileName",
    align: "center",
  },
  {
    title: "操作日期",
    dataIndex: "operationDate",
    key: "operationDate",
    align: "center",
  },
  {
    title: "结束时间",
    dataIndex: "endTime",
    key: "endTime",
    align: "center",
  },
  {
    title: "操作人",
    dataIndex: "operator",
    key: "operator",
    align: "center",
  },
  {
    title: "机构",
    dataIndex: "comName",
    key: "comName",
    align: "center",
  },
  {
    title: "状态",
    dataIndex: "states",
    key: "states",
    align: "center",
  },
  {
    title: "操作",
    dataIndex: "active",
    key: "active",
    align: "center",
  },
];
const importColumns = [
  {
    title: "文件名",
    dataIndex: "fileName",
    key: "fileName",
    align: "center",
  },
  {
    title: "文件笔数",
    dataIndex: "fileNumber",
    key: "fileNumber",
    align: "center",
  },
  {
    title: "操作人",
    dataIndex: "applicantName",
    key: "applicantName",
    align: "center",
  },
  {
    title: "机构",
    dataIndex: "comName",
    key: "comName",
    align: "center",
  },
  {
    title: "导入时间",
    dataIndex: "applicationTime",
    key: "applicationTime",
    align: "center",
  },
  {
    title: "导入结果",
    dataIndex: "approvalStatus",
    key: "approvalStatus",
    align: "center",
  },
  {
    title: "删除人",
    dataIndex: "delApproverName",
    key: "delApproverName",
    align: "center",
  },
  {
    title: "删除时间",
    dataIndex: "delApprovalTime",
    key: "delApprovalTime",
    align: "center",
  },
  {
    title: "删除状态",
    dataIndex: "delStatus",
    key: "delStatus",
    align: "center",
  },
  {
    title: "删除结果",
    dataIndex: "delApprovalStatus",
    key: "delApprovalStatus",
    align: "center",
  },
  {
    title: "操作",
    dataIndex: "active",
    key: "active",
    align: "center",
  },
];
const importDataSource = ref([]);
const historyDataSource = ref([]);
const pagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize;
    onSearch(areaType.value);
  },
});
const historyPagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    historyPagination.current = page;
    historyPagination.pageSize = pageSize;
    onHistory();
  },
});
const importPagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    importPagination.current = page;
    importPagination.pageSize = pageSize;
    onFeeRecord();
  },
});
const onSearch = (e: number) => {
  areaType.value = e;
  if (!props.selectedNodeId || props.selectedNodeId == 0) {
    message.error("请选择右侧树形结构");
    return;
  } else if (!searchForm.yearRange) {
    message.error("请选择年份");
    return;
  } else {
    const query = {
      treeData: props.selectedNodeId,
      year: searchForm.yearRange
        ? dayjs(searchForm.yearRange).format("YYYY")
        : "",
      page: pagination.current,
      limit: pagination.pageSize,
      type: areaType.value,
    };
    getOfflineHeatFeeApi(query).then((res: any) => {
      // console.log(res);
      dataSource.value = res.data;
      pagination.total = res.total;
    });
  }
};
const onList = () => {
  const query = {
    page: pagination.current,
    limit: pagination.pageSize,
    year: searchForm.yearRange
      ? dayjs(searchForm.yearRange).format("YYYY")
      : "",
    type: areaType.value,
    treeData: props.selectedNodeId,
  };
  getOfflineHeatFeeListApi(query).then((res: any) => {
    console.log(res);
    if (res.code == 200) {
      message.success(res.data);
    } else {
      message.error("导出失败");
    }
  });
};
const onHistory = () => {
  isHistory.value = true;
  getOfflineHeatFeeHistoryApi(
    historyPagination.current,
    historyPagination.pageSize,
    10
  ).then((res: any) => {
    console.log(res);
    historyDataSource.value = res.data;
    historyPagination.total = res.total;
  });
};
const onDown = (e: any) => {
  // console.log(e);
  const loading = message.loading({
    content: "下载中...",
    duration: 0,
  });

  try {
    // 下载地址拼接
    const url = e.urlAddress;

    // 使用a标签下载，避免X-Frame-Options错误
    const link = document.createElement("a");
    link.href = url;
    link.download = ""; // 触发下载而不是导航
    link.target = "_blank";
    link.style.display = "none";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    // 关闭loading
    setTimeout(() => {
      loading();
    }, 1000);
  } catch (error) {
    console.error("下载出错:", error);
    message.error("下载出错，请重试");
    loading();
  }
};
const onFeeRecord = () => {
  const query = {
    page: importPagination.current,
    limit: importPagination.pageSize,
  };
  getOfflineHeatFeeImportRecordApi(query).then((res: any) => {
    console.log(res);
    importDataSource.value = res.data;
    importPagination.total = res.total;
  });
};
const onTemplate = () => {
  const templatePath = "/Execl/按计量录入往年收费信息模版.xlsx";
  const templatePath2 = "/Execl/按面积录入往年收费信息模版.xlsx";
  const link = document.createElement("a");
  link.href = templatePath;
  link.download = templatePath.split("/").pop() || "";
  document.body.appendChild(link);
  link.click();
  link.remove();
  const link2 = document.createElement("a");
  link2.href = templatePath2;
  link2.download = templatePath2.split("/").pop() || "";
  document.body.appendChild(link2);
  link2.click();
  link2.remove();
};
const onDel = (e: any) => {
  console.log(e);
  if (e.approvalStatus === "同意") {
    message.error("已同意，不能删除");
  } else {
    delOfflineHeatFeeImportRecordApi(e.id).then((res: any) => {
      // console.log(res);
      message.success(res);
    });
  }
};
</script>
<style scoped>
:deep(.ant-segmented-item-selected) {
  font-weight: bold;
  color: #006be6;
}

:deep(.ant-form-item) {
  margin-bottom: 10px !important;
}
</style>
